package com.miluGame.service.impl;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.miluGame.entity.User;
import com.miluGame.mapper.UserMapper;
import com.miluGame.service.UserService;
import com.miluGame.util.Util;

@Service
public class UserServiceImpl implements UserService {

	@Autowired
	private UserMapper userMapper;
	
	private static final int pageSize=15;				//每页显示的数目
	
	@Override
	public List<User> queryAll(User t) {
		return userMapper.queryAll(null);
	}

	@Override
	public void delete(String id) throws Exception {
		userMapper.delete(id);
	}

	@Override
	public void update(User t) throws Exception {
		
	}

	@Override
	public User getById(String id) {
		
		return null;
	}

	@Override
	public void add(User t) throws Exception {
		userMapper.add(t);
	}

	@Override
	public void delete(String[] ids) throws Exception {
		
	}


	@Override
	public User login(String name, String password, HttpSession session,HttpServletRequest rsq,HttpServletResponse rsp) throws Exception {
		Map paramMap = new HashMap();
		User user= null;
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd:HH:mm:ss");
		if(name!=null&&password!=null){
			paramMap.put("name", name);
			paramMap.put("password", password);
			user = userMapper.login(paramMap);
			if(user!=null){
				user.setLastLoginTime(dateFormat.format(new Date()));
				userMapper.updateUserLoginTime(user);
				session.setAttribute("user", user);
				rsq.setAttribute("user", user);
			}
		}
		return user;
	}

	@Override
	public void queryUserPage(HttpSession session,HttpServletRequest rq,HttpServletResponse rsp) {
		int count = userMapper.countUsers();				//统计总数量
		int pageNum = Integer.parseInt(rq.getParameter("pageNum")==null?"0":rq.getParameter("pageNum").toString());				//获取当前页数
		int pageSum  =  count%pageSize==0?(count/pageSize-1):(count/pageSize);													//总页数
		Map paramMap = new HashMap();
		if(pageNum>pageSum){
			pageNum = pageSum;
		}
		paramMap.put("pageNum", pageNum);
		paramMap.put("pageSize", pageSize);
		paramMap.put("pageLine", pageNum*pageSize);
		List<User> users = userMapper.query(paramMap);
		rq.setAttribute("users", users);
		rq.setAttribute("pageSum", pageSum);
		rq.setAttribute("count", count);
		rq.setAttribute("pageNum", pageNum);
	}

	@Override
	public void updateUser(String userName, Integer able, Integer userId) throws Exception {
		User user = new User();
		user.setUserName(userName);
		user.setUserId(userId);
		user.setDisabled(able);
		userMapper.update(user);
	}

}
